import React, {
  useState,
  useRef,
  useEffect,
  CSSProperties,
  MutableRefObject,
} from 'react';
import { FormInstance } from '@arco-design/web-react/es/Form';
import { Input, Button, Message, Form } from '@arco-design/web-react';
import { sendCode } from '@/services/user';
import { TYPES } from './constant';
import styles from './index.module.less';

interface VerificationCodeProps {
  onPressEnter: () => void;
  formRef: MutableRefObject<FormInstance>;
  containerStyle?: CSSProperties;
  btnStyle?: CSSProperties;
  errorMsg?: string;
  placeholderMsg?: string;
  textMsg?: string;
  type?: string | undefined;
  // [key: string]: string;
}

function VerificationCode(props: VerificationCodeProps) {
  const {
    onPressEnter,
    formRef,
    containerStyle = {},
    btnStyle = {},
    errorMsg = '请输入正确的手机号',
    placeholderMsg = '请输入验证码',
    textMsg = '获取验证码',
    type = TYPES.register,
  } = props;
  const [lefttime, setLefttime] = useState(0);
  const [hasSend, setHasSend] = useState(false);
  const timer = useRef(null);

  const onSendCode = () => {
    if (formRef?.current) {
      const { mobile } = formRef.current.getFieldsValue();
      if (!mobile?.length || mobile.length !== 11) {
        Message.error(errorMsg);
        return;
      }
      if (lefttime > 0) {
        return;
      }
      if (timer.current) {
        clearInterval(timer.current);
      }
      sendCode({
        mobile,
        type,
      }).then((res) => {
        const { status } = res.data;
        if (status === 200) {
          setHasSend(true);
          setLefttime(60);
          timer.current = setInterval(() => {
            setLefttime((prev) => {
              if (prev <= 0) {
                clearInterval(timer.current);
                return 0;
              }
              return prev - 1;
            });
          }, 1000);
        }
      });
    }
  };

  useEffect(() => {
    return () => {
      timer.current = null;
      clearInterval(timer.current);
    };
  }, []);

  return (
    <Form.Item
      field="smsCode"
      rules={[{ required: true, message: '验证码不能为空' }]}
    >
      <Input
        style={containerStyle}
        className={styles['sendcode-input']}
        placeholder={placeholderMsg}
        onPressEnter={onPressEnter}
        addAfter={
          <Button
            onClick={onSendCode}
            type="text"
            htmlType="button"
            disabled={lefttime > 0}
            className={styles['sendcode-input-btn']}
            style={{
              ...btnStyle,
              color: '#6b9f17',
            }}
          >
            {lefttime > 0
              ? `重新发送(${lefttime})`
              : `${hasSend ? '重新发送' : textMsg} `}
          </Button>
        }
        afterStyle={{
          border: 'none',
        }}
      />
    </Form.Item>
  );
}
VerificationCode.displayName = 'VerificationCodePage';

export default VerificationCode;
